//
//  ConnectView.m
//  SipPhone
//
//  Created by 于国洋 on 2019/6/24.
//  Copyright © 2019 SJ. All rights reserved.
//

#import "ConnectView.h"

#import <AVFoundation/AVFoundation.h>

#import "SipManager.h"

@interface ConnectView ()

@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIButton *speakerButton;

@end

@implementation ConnectView

+ (instancetype)sharedView {
    static ConnectView *view;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        view = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil][0];
        view.frame = [UIScreen mainScreen].bounds;
    });
    
    return view;
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    [window addSubview:self];
    
    // 距离感应
    [UIDevice currentDevice].proximityMonitoringEnabled = true;
}

- (void)hide {
    [self removeFromSuperview];
    
    [UIDevice currentDevice].proximityMonitoringEnabled = false;
    
    if (_speakerButton.selected) {
        _speakerButton.selected = false;
        
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    }
}

- (void)setNumber:(NSString *)number {
    _number = number;
    
    _numberLabel.text = number;
}

- (void)setTime:(NSString *)time {
    _time = time;
    
    _timeLabel.text = time;
}

- (IBAction)handsFree {
    _speakerButton.selected = !_speakerButton.selected;
    
    if (_speakerButton.selected) { // 免提
        [UIDevice currentDevice].proximityMonitoringEnabled = false;
        
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
        
    } else {
        [UIDevice currentDevice].proximityMonitoringEnabled = true;

        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    }
}

- (IBAction)hangup {
    [[SipManager sharedManager] hangup];
}

@end
